package com.mbl.base.modular.mall.service.impl;

import com.mbl.base.core.utils.UtilOrderNoCreator;
import com.mbl.base.modular.mall.dto.GoodsAllinone;
import com.mbl.base.modular.mall.entity.*;
import com.mbl.base.modular.mall.mapper.GoodsMapper;
import com.mbl.base.modular.mall.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author lwj
 * @since 2020-02-27
 */
@Service
public class GoodsServiceImpl extends ServiceImpl<GoodsMapper, Goods> implements IGoodsService {
    @Autowired
    private IGoodsSpecificationService specificationService;
    @Autowired
    private IGoodsAttributeService attributeService;
    @Autowired
    private IGoodsProductService productService;
    @Autowired
    private ICategoryService categoryService;
    @Transactional
    @Override
    public boolean create(GoodsAllinone goodsAllinone) {
        Goods goods = goodsAllinone.getGoods();
        GoodsAttribute[] attributes = goodsAllinone.getAttributes();
        GoodsSpecification[] specifications = goodsAllinone.getSpecifications();
        GoodsProduct[] products = goodsAllinone.getProducts();
        //商品编号
        String goodsSn = UtilOrderNoCreator.createOrderNo();
        goods.setGoodsSn(goodsSn);
        String name = goods.getName();

        // 商品表里面有一个字段retailPrice记录当前商品的最低价
        BigDecimal retailPrice = new BigDecimal(Integer.MAX_VALUE);
        for (GoodsProduct product : products) {
            BigDecimal productPrice = product.getPrice();
            if (retailPrice.compareTo(productPrice) == 1) {
                retailPrice = productPrice;
            }
        }
        goods.setRetailPrice(retailPrice);
        goods.setVipPrice(goodsAllinone.getProducts()[0].getVipPrice());
        // 商品基本信息表_goods
        save(goods);

        //将生成的分享图片地址写入数据库
//        String url = qCodeService.createGoodShareImage(goods.getId().toString(), goods.getPicUrl(), goods.getName());
//        if (!StringUtils.isEmpty(url)) {
//            goods.setShareUrl(url);
//            if (goodsService.updateById(goods) == 0) {
//                throw new RuntimeException("更新数据失败");
//            }
//        }

        // 商品规格表_goods_specification
        for (GoodsSpecification specification : specifications) {
            specification.setGoodsId(goods.getId());
            specificationService.save(specification);
        }

        // 商品参数表_goods_attribute
        for (GoodsAttribute attribute : attributes) {
            attribute.setGoodsId(goods.getId());
            attributeService.save(attribute);
        }

        // 商品货品表_product
        for (GoodsProduct product : products) {
            product.setGoodsId(goods.getId());
            productService.save(product);
        }
        return true;
    }

    @Transactional
    @Override
    public boolean update(GoodsAllinone goodsAllinone) {

        Goods goods = goodsAllinone.getGoods();
        GoodsAttribute[] attributes = goodsAllinone.getAttributes();
        GoodsSpecification[] specifications = goodsAllinone.getSpecifications();
        GoodsProduct[] products = goodsAllinone.getProducts();

        //将生成的分享图片地址写入数据库
//        String url = qCodeService.createGoodShareImage(goods.getId().toString(), goods.getPicUrl(), goods.getName());
//        goods.setShareUrl(url);

        // 商品表里面有一个字段retailPrice记录当前商品的最低价
        BigDecimal retailPrice = new BigDecimal(Integer.MAX_VALUE);
        for (GoodsProduct product : products) {
            BigDecimal productPrice = product.getPrice();
            if (retailPrice.compareTo(productPrice) == 1) {
                retailPrice = productPrice;
            }
        }
        goods.setRetailPrice(retailPrice);
        goods.setVipPrice(goodsAllinone.getProducts()[0].getVipPrice());
        // 商品基本信息表_goods
        if (!updateById(goods)) {
            throw new RuntimeException("更新数据失败");
        }
        Long gid = goods.getId();
        // 商品规格表_goods_specification
        for (GoodsSpecification specification : specifications) {
            // 目前只支持更新规格表的图片字段
            if (specification.getUpdateTime() == null) {
                specification.setSpecification(null);
                specification.setValue(null);
                specificationService.updateById(specification);
            }
        }

        // 商品货品表_product
        for (GoodsProduct product : products) {
            if (product.getUpdateTime() == null) {
                productService.updateById(product);
            }
        }

        // 商品参数表_goods_attribute
        for (GoodsAttribute attribute : attributes) {
            if (attribute.getId() == null || attribute.getId().equals(0)) {
                attribute.setGoodsId(goods.getId());
                attributeService.save(attribute);
            } else if (attribute.getFlag()) {
                attributeService.removeById(attribute.getId());
            } else if (attribute.getUpdateTime() == null) {
                attributeService.updateById(attribute);
            }
        }

        // 这里需要注意的是购物车_cart有些字段是拷贝商品的一些字段，因此需要及时更新
        // 目前这些字段是goods_sn, goods_name, price, pic_url
//        for (GoodsProduct product : products) {
//            cartService.updateProduct(product.getId(), goods.getGoodsSn(), goods.getName(), product.getPrice(), product.getUrl());
//        }

        return true;
    }

    @Override
    public Object detail(Integer id) {
        Goods goods = getById(id);
        List<GoodsProduct> products = productService.query().eq("goods_id",id).list();
        List<GoodsSpecification> specifications = specificationService.query().eq("goods_id",id).list();
        List<GoodsAttribute> attributes = attributeService.query().eq("goods_id",id).list();
        Integer categoryId = goods.getCategoryId();
        Category category = categoryService.getById(categoryId);
        Integer[] categoryIds = new Integer[]{};
        if (category != null) {
            Integer parentCategoryId = category.getPid();
            categoryIds = new Integer[]{parentCategoryId, categoryId};
        }

        Map<String, Object> data = new HashMap<>();
        data.put("goods", goods);
        data.put("specifications", specifications);
        data.put("products", products);
        data.put("attributes", attributes);
        data.put("categoryIds", categoryIds);
        return data;
    }
}
